<?php

namespace App\Console\Commands;

use App\Article;
use App\Permission;
use App\Studyfav;
use App\Utils;
use Illuminate\Console\Command;
use DB;
use App\Solve;
use App\Task;
use App\User;
use App\Comment;
use Auth;

//use Illuminate\Foundation\Inspiring;

class Admin extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'calculate score';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //if (!Auth::check()) return;
        //if (Permission::userid_is_norank(Auth::user()->id)) return;

        $t1 = time();
        $html = '';
        $no_rank_task = array(36, 69);
        $extrat = array(25, 41, 72, 73, 76, 95,133,140);
        $uextrats = array();
        // 更新最优化问题的答案的score
        foreach ($extrat as $t) {
            if ($t == 25 || $t == 95)
                $arr = DB::select("select max(score) as s,userid,id from solves where type=0 and taskid=" . $t . " group by userid order by s desc");
            else
                $arr = DB::select("select min(score) as s,userid,id from solves where type=0 and taskid=" . $t . " group by userid order by s asc");
            $sz = count($arr);
            $s = 500;
            for ($i = 0; $i < $sz;) {
                $ts = 0;
                for ($j = $i; $j < $sz; $j++) {
                    if ($arr[$i]->s != $arr[$j]->s) break;
                    $ts += $s;
                    $s /= 2;
                }
                $num = $j - $i;
                for ($k = $i; $k < $j; $k++) {
                    $rs = intval($ts / $num * 100);
                    if ($rs < 100) $rs = 100;
                    $data = DB::update("update solves set rscore=" . $rs . " where id=" . $arr[$k]->id . " limit 1");
                    $uid = $arr[$k]->userid;
                    if (!isset($uextrats[$uid])) $uextrats[$uid] = 0;
                    $uextrats[$uid] += $rs;
                }
                $i = $j;
            }
        }
        $html .= ("用户数:" . (User::count() - 16) . "\n<br>");
        $html .= ("解题尝试次数:" . Solve::count() . "\n<br>");
        $html .= ("解题正确次数:" . Solve::where('type', '=', 0)->count() . "\n<br>");

        $tasks = array();
		$task_cntdata = DB::select("select count(*) as cc from tasks");
		$task_cnt = $task_cntdata[0]->cc;
        //更新非最优化题目的score
        for ($i = 1; $i <= $task_cnt; $i++) {
            if ($i == 104) continue;
            if (in_array($i, $extrat)) continue;
            $task = Task::find($i);
            //去掉shinian账号之后的做出题的人数
            $cnta = DB::select("select count(distinct userid) as cc from solves where type=0 and userid!=19 and taskid=" . $i);
            $cnt = $cnta[0]->cc;
            if ($cnt == 0) $score = 1000;
            else $score = 1000 / $cnt;

            if ($score < 1) $score = 1;
            //36-大侠饶命, 69-Share 不纳入计算
            if (in_array($i, $no_rank_task)) $score = 0;

            $task->score = (int)($score * 100);
            $task->save();
            $tasks[$i] = $task->score;
            $cntb = DB::select("select count(distinct userid) as cc from solves where taskid=" . $i);
            $cnt2 = $cntb[0]->cc;
            $html .= ("第" . $i . "题 | <a href='#'> [" . $task->title . "]</a> | 做出来的人数:" . $cnt . '/' . ($cnt + $cnt2) . ' | 分数:' . $score . '<br>');
        }
        //更新所有user的score,rank,做题数
        $users = User::all()->sortbyDesc('score');
        $rank = 0;
        foreach ($users as $user) {
			try{
            if (Permission::userid_is_norank($user->id)) continue;
            $rank++;
            $s = 0;
            $solves = Solve::whereUseridAndType($user->id, 0)->groupby("taskid")->get();

            $tcnt = 0;
            foreach ($solves as $solve) {
                $taskid = $solve->taskid;
                if (in_array($taskid, $extrat)) continue;
                //36-大侠饶命, 69-Share 不纳入计算
                if (in_array($taskid, $no_rank_task)) continue;
                $tcnt++;
                if ($taskid == 44) {
                    $s += $solve['score'] * 100;
                } else if ($taskid == 80) {
                    $s += $solve['score'] * ($solve['score'] + 1) * 25;
                } else
                    $s += $tasks[$taskid];
            }
            if ($s == 0) continue;
            if (isset($uextrats[$user->id]))
                $s += $uextrats[$user->id];

            $user->score = $s;
            $user->solveNum = $tcnt;
            $user->rank = $rank;
            $user->save();
            $html .= ($user->id . ' |  <font color="red">' . $user->name . "</font>  | " . date("Y-m-d H:i:s", $user->last_login_time));
            $html .= (' | <a href="/u/' . Utils::id2url($user->id) . '">' . ($s / 100) . "</a><br>");
			}catch(Exception $e){
				var_dump("error:".$e);
			}
        }
		unset($users);
//
//        $comments = Comment::all();
//        foreach ($comments as $c) {
//            $c->score = 0;
//            $voted_users = Studyfav::where('studyid', $c->id)->where('type', 1)->groupBy('userid')->get();
//            foreach ($voted_users as $user) {
//                if ($c->userid === $user->userid)
//                    continue;
//                $user = User::find($user->userid);
//                if ($user != null) {
//                    $c->score += intval($user->score / 100);
//                }
//            }
//            $c->save();
//        }
//        $articles = Article::all();
//        foreach ($articles as $article) {
//            $article->score = 0;
//            $voted_users = Studyfav::where('studyid', $article->id)->where('type', 2)->groupBy('userid')->get();
//            foreach ($voted_users as $user) {
//                if ($article->userid === $user->userid)
//                    continue;
//                $user = User::find($user->userid);
//                if ($user != null) {
//                    $article->score += intval($user->score / 100);
//                }
//            }
//            $article->save();
//        }

        $t3 = time();

        $outfile = fopen("/home/xingshi/admin_calc.html", "w");
        fwrite($outfile, '更新时间:' . date("Y-m-d H:i:s", time()) . '<br>');
        fwrite($outfile, '耗时:' . ($t3 - $t1) / 60 . '分钟<br>');
        fwrite($outfile, $html);
        fclose($outfile);
    }
}
